package io.esirong.manager;

import android.content.Context;
import android.content.SharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.esirong.Resource;


/**
 * AccessTokenCache
 * Created by 黄嵘才 on 2017/7/10.
 */

class AccessTokenCache {

    static final String CACHED_ACCESS_TOKEN_KEY
            = "io.silvrr.AccessTokenManager.CachedAccessToken";
    private final SharedPreferences appPreferences;

    AccessTokenCache() {
        this(Resource.context().getApplicationContext());
    }

    AccessTokenCache(Context context) {
        this.appPreferences = context.getSharedPreferences("", Context.MODE_PRIVATE);
    }

    @Nullable
    public AccessToken load() {
        AccessToken accessToken = null;
        if (hasCachedAccessToken()) {
            // If we have something cached, we try to use it; even if it is invalid, do not fall
            // back to a legacy caching strategy.
            accessToken = getCachedAccessToken();
        }

        return accessToken;
    }

    public void save(@NonNull AccessToken accessToken) {

        JSONObject jsonObject;
        try {
            jsonObject = accessToken.toJSONObject();
            appPreferences.edit().putString(CACHED_ACCESS_TOKEN_KEY, jsonObject.toString()).apply();
        } catch (JSONException e) {
            // Can't recover
        }
    }

    public void clear() {
        appPreferences.edit().remove(CACHED_ACCESS_TOKEN_KEY).apply();
    }

    private boolean hasCachedAccessToken() {
        String value = appPreferences.getString(CACHED_ACCESS_TOKEN_KEY, null);
        return value != null;
    }

    private AccessToken getCachedAccessToken() {
        String jsonString = appPreferences.getString(CACHED_ACCESS_TOKEN_KEY, null);
        if (jsonString != null) {
            try {
                JSONObject jsonObject = new JSONObject(jsonString);
                return AccessToken.createFromJSONObject(jsonObject);
            } catch (JSONException e) {
                return null;
            }
        }
        return null;
    }
}
